package com.zy.xuanwo.acitivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.xuanwo.R;
import com.zy.xuanwo.bean.ErrorBean;
import com.zy.xuanwo.bean.RegisterBean;
import com.zy.xuanwo.utils.RegexUtils;
import com.zy.xuanwo.utils.ToastUtils;
import com.zy.xuanwo.utils.URLConstants;
import com.zy.xuanwo.view.CustomToast;
import com.zy.xuanwo.zyc.portal.bean.ErrorMessag;
import com.zy.xuanwo.zyc.portal.callback.GetCommonResultListener;
import com.zy.xuanwo.zyc.portal.service.imp.PortalMagger;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by njb on 2016/7/3.
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    @Bind(R.id.left_sliding_menu_iv)
    ImageView mBack;
    @Bind(R.id.phoner_number_et)
    EditText phonerNumberEt;
    @Bind(R.id.password_et)
    EditText passwordEt;
    @Bind(R.id.suer_password_et)
    EditText suerPasswordEt;
    @Bind(R.id.verification_code_et)
    EditText verificationCodeEt;
    @Bind(R.id.send_code_btn)
    Button sendCodeBtn;
    @Bind(R.id.register_btn)
    Button registerBtn;
    private RegisterBean mRegisterBean;
    private String userName;
    private ErrorBean mErrorBean;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x124) {
                int i = (int) msg.obj;
                sendCodeBtn.setText(i + "s");
                if (i == 1 && !RegisterActivity.this.isFinishing()) {
                    sendCodeBtn.setClickable(true);
                    sendCodeBtn.setText("重新发送");
                    sendCodeBtn.setBackgroundColor(getResources().getColor(R.color.white));
                }
            }

        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initView();

    }

    /**
     * 初始化控件
     */
    private void initView() {
        passwordEt.setImeOptions(EditorInfo.IME_ACTION_DONE);
        passwordEt.setImeOptions(EditorInfo.IME_ACTION_GO);
        passwordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // 点击虚拟键盘的done
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || actionId == EditorInfo.IME_ACTION_GO) {
                    register();
                }
                return false;
            }


        });
    }


    private void doVerificationCodeRequest() {
        String userName = phonerNumberEt.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.showShort("手机号或邮箱不能为空");
            return;
        }
        sendCodeBtn.setClickable(false);
        sendCodeBtn.setBackgroundColor(getResources().getColor(R.color._D8D8D8));
        countDown();
        if (RegexUtils.checkEmail(userName)) {
           getVerificationCode(URLConstants.EMAIL_VERIFICATION_CODE_URL,userName);
        } else if (RegexUtils.checkMobile(userName)) {
            getVerificationCode(URLConstants.SMS_VERIFICATION_CODE_URL,userName);
        }
    }

    private void getVerificationCode(final String url,String userName) {
        OkHttpUtils.post()
                .url(url)
                .addParams("username", userName)
                .addHeader("token", "446f8fd7-8fc3-426d-8c70-283c021dd380")
                .addHeader("X-Request-Sign", "f033abaf9eac94ffc03d25ee6be445e3, 1467598209")
                .addHeader("X-Application-Id", "3d632345-abd5-4c7c-b157-6d12cd3f0dde")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("response", e + "");
                        ToastUtils.showShort("发送失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("response", response + "");
                        if (URLConstants.EMAIL_VERIFICATION_CODE_URL.equals(url)) {
                            ToastUtils.showShort("验证码已发送至邮箱，请查收");
                        } else if (URLConstants.SMS_VERIFICATION_CODE_URL.equals(url)) {
                            ToastUtils.showShort("验证码已发送至手机");
                        }
                    }
                });
    }
    private void register() {
        final String userName = phonerNumberEt.getText().toString().trim();
        String password = passwordEt.getText().toString().trim();
        String surePassword = suerPasswordEt.getText().toString().trim();
        String verificationCode = verificationCodeEt.getText().toString().trim();

        if (checkInput(userName, password, surePassword, verificationCode)) {
            OkHttpUtils.post()
                    .url(URLConstants.RIGISTER_URL)
                    .addHeader("token", "446f8fd7-8fc3-426d-8c70-283c021dd380")
                    .addHeader("X-Request-Sign", "f033abaf9eac94ffc03d25ee6be445e3, 1467598209")
                    .addHeader("X-Application-Id", "3d632345-abd5-4c7c-b157-6d12cd3f0dde")
                    .addParams("username", userName)
                    .addParams("password", password)
                    .addParams("surepassword", surePassword)
                    .addParams("verification_code", verificationCode)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("response", e + "");

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.e("response", response + "");
                                mErrorBean = new Gson().fromJson(response,ErrorBean.class);
                                int code = mErrorBean.getCode();
                                Log.e("response", mErrorBean.getMessage());
                                //判断返回的code
                                checkSignUpCode(code);
                                Log.e("response", String.valueOf(code));
                            Intent resultIntent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString("account", userName);
                            resultIntent.putExtras(bundle);
                            RegisterActivity.this.setResult(RESULT_OK, resultIntent);
                            RegisterActivity.this.finish();
                        }
                    });
        }
    }


    /**
     * 检验服务器返回的code
     *
     * @param code
     */
    private void checkSignUpCode(int code) {
        if (code == 403) {
            Toast.makeText(RegisterActivity.this,"用户已注册" , Toast.LENGTH_SHORT).show();
        } else if (code == 200) {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("account", userName);
            resultIntent.putExtras(bundle);
            this.setResult(RESULT_OK, resultIntent);
            RegisterActivity.this.finish();
        } else if(code == 400){
            Toast.makeText(RegisterActivity.this,"用户输入错误，格式不正确" , Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(RegisterActivity.this, "未定义异常", Toast.LENGTH_SHORT).show();
        }

    }


    private boolean checkInput(String userName, String password, String surePassword, String verificationCode) {

        if (TextUtils.isEmpty(userName)) {
            ToastUtils.showShort("手机号或邮箱不能为空");
        } else if (TextUtils.isEmpty(password)) {
            ToastUtils.showShort("密码不能为空");
        } else if (TextUtils.isEmpty(surePassword)) {
            ToastUtils.showShort("确认密码不能为空");
        } else if (TextUtils.isEmpty(verificationCode)) {
            ToastUtils.showShort("验证码不能为空");
        } else {
            if (!(RegexUtils.checkMobile(userName) || RegexUtils.checkEmail(userName))) {
                ToastUtils.showShort("手机号或邮箱格式不正确");
            } else if (!password.equals(surePassword)) {
                ToastUtils.showShort("两次输入的密码不一致");
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 倒计时
     */
    private void countDown() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 60; i >= 1; i--) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = handler.obtainMessage();
                    message.what = 0x124;
                    message.obj = i;
                    handler.sendMessage(message);
                }
            }
        }.start();
    }

    @OnClick({R.id.left_sliding_menu_iv, R.id.send_code_btn, R.id.register_btn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_sliding_menu_iv:
                RegisterActivity.this.finish();
                break;
            case R.id.send_code_btn:
                doVerificationCodeRequest();
                break;
            case R.id.register_btn:
                register();
                break;
            default:
                break;
        }
    }


}
